package com.bestcem.xm.member.mq.receiver.biz;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.bestcem.xm.common.core.constant.StreamMqBinderConstants;
import com.bestcem.xm.member.mq.message.*;
import com.bestcem.xm.member.service.*;
import com.bestcem.xm.member.service.mq.send.MemberMessageSendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class ReceiverService {
    @Resource
    private MemberMessageSendService memberMessageSendService;
    @Resource
    private SendMemberService sendMemberService;
    @Resource
    private MemberMessageService memberMessageService;
    @Resource
    private WechatService wechatService;
    @Resource
    private SourceCardService sourceCardService;
    @Resource
    private GroupService groupService;
    @Resource
    private MemberMqHandler memberMqHandler;
    @Resource
    private MemberUserGroupService memberUserGroupService;
    /*@Resource
    private PackMqHandler packMqHandler;*/

    /**
     * 分组规则修改
     */
    public void groupConditionMod(GenericMessage<GroupingMessage> message) {
        GroupingMessage msg = message.getPayload();
        if (log.isInfoEnabled()) {
            log.info("【联系人】received group condition modification message: {}", JSONUtil.toJsonStr(msg));
        }
        groupService.groupMembers(msg);
    }

    /**
     * 联系人删除
     */
    public void groupDeleted(GenericMessage<GroupDeletedMessage> message) {
        GroupDeletedMessage msg = message.getPayload();
        if (log.isInfoEnabled()) {
            log.info("【联系人】 联系人删除队列收到消息:{}", JSONUtil.toJsonStr(msg));
        }
        groupService.updateMemberGroups(msg);
    }

    /**
     * 创建用户
     */
    public void userCreated(GenericMessage<UserMessage> message) {
        UserMessage msg = message.getPayload();
        if (log.isInfoEnabled()) {
            log.info("【联系人】 创建用户队列收到消息:{}", JSONUtil.toJsonStr(msg));
        }
        try {
            memberMqHandler.createInnerMemberByCreateUser(msg);
        } catch (Exception e) {
            log.error("【联系人】 创建用户同步创建内部联系人失败", e);
        }
    }

    /**
     * 更新用户同步更新内部联系人
     */
    public void userUpdated(GenericMessage<UserMessage> message) {
        UserMessage msg = message.getPayload();
        if (log.isInfoEnabled()) {
            log.info("【联系人】 更新用户队列收到消息:{}", JSONUtil.toJsonStr(msg));
        }
        try {
            memberMqHandler.updateInnerMemberByUpdateUser(msg);
        } catch (Exception e) {
            log.error("【联系人】 更新用户同步更新内部联系人", e);
        }
    }

    /**
     * 机构创建
     */
    public void orgCreated(GenericMessage<OrgCreatedMessage> message) {
        OrgCreatedMessage msg = message.getPayload();
        if (log.isInfoEnabled()) {
            log.info("【联系人】 机构创建队列收到消息:{}", JSONUtil.toJsonStr(msg));
        }
        try {
            // 创建默认标签分组及标签
            memberMqHandler.createDefaultLabelGroup(msg);
            // 创建联系人可见范围
            memberMqHandler.createMemberDisplayRange(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存联系人足迹
     */
    public void footprintSave(GenericMessage<FootprintMessage> message) {
        FootprintMessage msg = message.getPayload();
        if (log.isInfoEnabled()) {
            log.info("【联系人】保存联系人足迹队列收到消息:{}", JSONUtil.toJsonStr(msg));
        }
        memberMqHandler.saveFootprint(msg);
    }

    /**
     * 联系人创建、联系人更新-调度至分组
     */
    public void memberCreationUpd(GenericMessage<MemberCreationUpdMessage> message) {
        MemberCreationUpdMessage msg = message.getPayload();
        if (log.isInfoEnabled()) {
            log.info("【联系人】 联系人创建、联系人更新队列收到消息:{}", JSONUtil.toJsonStr(msg));
        }
        groupService.groupMember(msg);
    }

    /**
     * 联系人本地缓存
     */
    public void memberDb(GenericMessage<SourceCardMessage> message) {
        SourceCardMessage msg = message.getPayload();
        if (log.isInfoEnabled()) {
            log.info("【联系人】 联系人本地缓存队列收到消息:{}", JSONUtil.toJsonStr(msg));
        }
        sourceCardService.handleSourceCard(msg);
    }

    /**
     * 删除联系人
     */
    public void memberDeleted(GenericMessage<MemberDeletedMessage> message) {
        MemberDeletedMessage msg = message.getPayload();
        if (log.isInfoEnabled()) {
            log.info("【联系人】 删除联系人队列收到消息:{}", JSONUtil.toJsonStr(msg));
        }
        memberMessageService.handleMemberDelete(msg);
    }

    /**
     * 打标签消息
     */
    public void memberMemberSlice(GenericMessage<MemberSliceMessage> message) {
        if (log.isInfoEnabled()) {
            log.info("【联系人】 打标签队列收到消息:{}", JSONUtil.toJsonStr(message.getPayload()));
        }
        sendMemberService.sendMembers(message.getPayload());
    }

    /**
     * 同步所有已授权的公众号粉丝数据 延时队列
     */
    public void wechatMemberScheduleSyncDelay(GenericMessage<WechatMemberSyncMessage> message) {
        WechatMemberSyncMessage msg = message.getPayload();
        if (log.isInfoEnabled()) {
            log.info("【联系人】【延时队列】同步所有已授权的公众号粉丝数据");
            msg.setRetryCount(msg.getRetryCount() + 1);
            wechatService.sendWxScheduleSyncMessage(msg);
        }
    }

    /**
     * 同步微信粉丝
     */
    public void memberWechatMemberSchedule(GenericMessage<WechatMemberSyncMessage> message) {
        WechatMemberSyncMessage msg = message.getPayload();
        if (log.isInfoEnabled()) {
            log.info("【联系人】 同步微信粉丝队列收到消息:{}", JSONUtil.toJsonStr(msg));
        }
        if (msg.getRetryCount() > StreamMqBinderConstants.RETRY_COUNT) {
            log.error("【联系人】处理同步所有已授权的公众号粉丝数据{}, 重试次数超过 {} 次", JSONUtil.toJsonStr(msg), StreamMqBinderConstants.RETRY_COUNT);
        } else {
            // 同步微信粉丝
            wechatService.scheduleSyncWxMember(msg);
        }
    }

    /**
     * 微信同步联系人(调度) 延时队列
     */
    public void wechatMemberSyncDelayDelay(GenericMessage<WechatMemberSyncMessage> message) {
        WechatMemberSyncMessage msg = message.getPayload();
        if (log.isInfoEnabled()) {
            log.info("【联系人】微信同步联系人(调度) 延迟队列收到消息:{}", JSONUtil.toJsonStr(msg));
        }
        msg.setRetryCount(msg.getRetryCount() + 1);
        wechatService.sendWxScheduleSyncMessage(msg);
    }

    /**
     * 答卷提交
     */
    public void surveyRespondentSubmit(GenericMessage<RespondentDataMessage> msg) {
        if (log.isInfoEnabled()) {
            log.info("【联系人】 答卷提交队列收到消息:{}", JSONUtil.toJsonStr(msg.getPayload()));
        }
        RespondentDataMessage dto = msg.getPayload();
        memberMqHandler.createMemberByRespondentSubmit(dto);
        //20231112工单处理必须在创建联系人后面，不然工单足迹同步不过来，
        //答题结果生成联系人后才有memberid，所以需要在创建联系人后面处理，其他短信投放、邮件投放联系人工单足迹没有这个问题
        //生成联系人+触发工单才有此问题
        memberMessageSendService.startTicketSurveyRespondentSubmitSend(dto);
    }

    /**
     * 答卷时授权获取微信账号信息
     */
    public void syncWechatAccountInfo(GenericMessage<SyncWechatAccountInfoMessage> message) {
        SyncWechatAccountInfoMessage msg = message.getPayload();
        if (log.isInfoEnabled()) {
            log.info("【联系人】答卷时授权获取微信账号信息消息:{}", JSONUtil.toJsonStr(msg));
        }
        wechatService.syncWechatAccountInfo(msg);
    }

    /**
     * 监听用户层级变动
     */
    public void userGroupChanged(GenericMessage<SyncMemberStoreMessage> message) {
        SyncMemberStoreMessage msg = message.getPayload();
        if (log.isInfoEnabled()) {
            log.info("【联系人】监听用户层级变动消息:{}", JSONUtil.toJsonStr(msg));
        }
        memberUserGroupService.flush(msg.getOrgId());
    }

    /**
     * 微信公众号授权
     */
    public void wechatOfficialAccountGranted(GenericMessage<WechatOfficialAccountGrantedMessage> message) {
        WechatOfficialAccountGrantedMessage msg = message.getPayload();
        if (log.isInfoEnabled()) {
            log.info("【联系人】微信公众号授权消息:{}", msg);
        }
        wechatService.syncWechatOfficialAccountGranted(msg);
    }

    /**
     * 监听联系人延迟队列消息/group member 重新分组
     */
    public void memberRegroupMember(GenericMessage<MemberCreationUpdMessage> message) {
        MemberCreationUpdMessage msg = message.getPayload();
        if (log.isInfoEnabled()) {
            log.info("【联系人】开始消费联系人延迟队列消息:{}", JSON.toJSONString(msg));
        }
        groupService.groupMember(msg);
    }

    /**
     * 监听联系人延迟队列消息/group members 重新分组
     */
    public void memberRegroupMembers(GenericMessage<GroupingMessage> message) {
        GroupingMessage msg = message.getPayload();
        if (log.isInfoEnabled()) {
            log.info("【联系人】regroup members success, message: {}", msg);
        }
        groupService.groupMembers(msg);
    }

    /**
     * 微信公众号同步打开与关闭延迟队列消息
     */
    public void wechatMemberSyncDelay(GenericMessage<WechatMemberSyncMessage> message) {
        wechatService.sendWxSyncMessage(message.getPayload());
    }
}
